#/usr/bin/env python
# -*- coding: utf-8 -*-

import requests
import json
import time
import datetime
#from dateutil.relativedelta import relativedelta
import pymysql

print('>>> 开始连接mysql数据库>>>股票')
dbmysql = pymysql.connect(host='72.19.12.227', port=3306,
                          user='root',
                          passwd='lihao123', db='v3board', charset='utf8')
dictCursorclass = pymysql.cursors.DictCursor


class Bandwagonhost(object):

    def __init__(self, veid, api_key):
        self.veid = veid
        self.api_key = api_key




    def queryMySql(self, sql, dictCursor):
        if sql == "":
            return ""
        try:
            with dbmysql.cursor(dictCursor) as cursor:
                cursor.execute(sql)
                data = cursor.fetchall()
                return data
        except Exception as e:
            print(F'>>> 查询数据失败,查询语句为：{sql}；\n错误信息为：{e}')
        finally:
            print("")
            # dbmysql.close()



    def Caltime(self,date1, date2):

        # %Y-%m-%d为日期格式，其中的-可以用其他代替或者不写，但是要统一，同理后面的时分秒也一样；可以只计算日期，不计算时间。

        # date1=time.strptime(date1,"%Y-%m-%d %H:%M:%S")

        # date2=time.strptime(date2,"%Y-%m-%d %H:%M:%S")

        date1 = time.strptime(date1, "%Y-%m-%d")

        date2 = time.strptime(date2, "%Y-%m-%d")

        # 根据上面需要计算日期还是日期时间，来确定需要几个数组段。下标0表示年，小标1表示月，依次类推...

        # date1=datetime.datetime(date1[0],date1[1],date1[2],date1[3],date1[4],date1[5])

        # date2=datetime.datetime(date2[0],date2[1],date2[2],date2[3],date2[4],date2[5])

        date1 = datetime.datetime(date1[0], date1[1], date1[2])

        date2 = datetime.datetime(date2[0], date2[1], date2[2])

        # 返回两个变量相差的值，就是相差天数

        return date2 - date1
    def start_vps(self):
        r = requests.get('https://api.64clouds.com/v1/start?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def stop_vps(self):
        r = requests.get('https://api.64clouds.com/v1/stop?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def restart_vps(self):
        r = requests.get('https://api.64clouds.com/v1/restart?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def kill_vps(self):
        r = requests.get('https://api.64clouds.com/v1/kill?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def get_server_info(self):
        r = requests.get('https://api.64clouds.com/v1/getServiceInfo?veid=' + self.veid + '&api_key=' + self.api_key)
        #print( json.dumps(r.json(), indent=1))
        data = json.dumps(r.json(), indent=1)
        currentTime = time.time()
        resetTime = json.loads(data)['data_next_reset']
        startTime = resetTime
        # 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
        timeArray = time.localtime(resetTime)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        datetime.date.today()
        resetDate = time.strftime("%Y-%m-%d", timeArray)
        day = self.Caltime(str(datetime.date.today()), resetDate).days

        # 当前时间减一个月
        # reset_date = datetime.datetime(timeArray.tm_year, timeArray.tm_mon, timeArray.tm_mday, timeArray.tm_hour,
        #                                timeArray.tm_min,
        #                                timeArray.tm_sec) - relativedelta(months=+1)

        use_plan = str(round((int(json.loads(data)['data_counter']) / 1073741824), 2)) + "/" + str(
            int(json.loads(data)['plan_monthly_data']) / 1073741824) + "G"
        percent = str(
            round(int(json.loads(data)['data_counter']) * 100 / int(json.loads(data)['plan_monthly_data']), 2)) + "%"
        ip = json.loads(data)['ip_addresses'][0]

        residue = str(round(int(json.loads(data)['plan_monthly_data']) / 1073741824 - int(
            json.loads(data)['data_counter']) / 1073741824, 2)) + "G"

        subTitle = "已用: " + percent + ", " + use_plan + " 剩余: " + residue
        cur = dbmysql.cursor()
        sql = "select group_id from v2_server_v2ray where  host = '" + ip + "'"
        datasql = self.queryMySql(sql, dictCursorclass)
        if day <=10 and round(int(json.loads(data)['data_counter']) * 100 / int(json.loads(data)['plan_monthly_data']), 2) < 0.5 :

            if '1' not in datasql[0]['group_id'] :
                sql = "update v2_server_v2ray set  group_id = '[\"3\",\"4\",\"1\"]' where host = '"+ ip +"'"
                print(sql)
                cur.execute(sql)
                cur.connection.commit()
                cur.close()
                requests.get("http://124.223.11.108:9080/gUw5GwL3yRozyuTKCD2RBY/服务器流量自动更新/加入成功"+ip)
        else:
            if '1' in datasql[0]['group_id'] :
                sql = "update v2_server_v2ray set  group_id = '[\"3\",\"4\"]' where host = '" + ip + "'"
                print(sql)
                cur.execute(sql)
                cur.connection.commit()
                cur.close()
                requests.get("http://124.223.11.108:9080/gUw5GwL3yRozyuTKCD2RBY/服务器流量自动更新/去掉成功"+ip)

        # residueFlow = averageFlow(currentTime, resetTime, data.plan_monthly_data - data.data_counter)
        # usedFlow = averageFlow(startTime, currentTime, data.data_counter)

        msg1 = "主机: " + ip
        # msg2 = "剩余: " + residueTimes
        msg3 = "重置时间: " + str(otherStyleTime)
        message = msg1 + "\n" + subTitle + "\n" + msg3
        print(message)
        return message

    def get_live_service_info(self):
        r = requests.get('https://api.64clouds.com/v1/getLiveServiceInfo?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def get_available_os(self):
        r = requests.get('https://api.64clouds.com/v1/getAvailableOS?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def reinstall_os(self, os):
        r = requests.get(
            'https://api.64clouds.com/v1/reinstallOS?os=' + os + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def reset_root_password(self):
        r = requests.get('https://api.64clouds.com/v1/resetRootPassword?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    # TODO draw a fig instead
    def get_raw_usage_stats(self):
        r = requests.get('https://api.64clouds.com/v1/getRawUsageStats?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def set_hostname(self, newHostname):
        server = self.get_server_info()
        if server.json()['vm_type'] != 'ovz':
            print( 'only for ovz servers')
            return False
        else:
            r = requests.get(
                'https://api.64clouds.com/v1/setHostname?newHostname=' + newHostname
                + '&veid=' + self.veid + '&api_key=' + self.api_key)
            print( json.dumps(r.json(), indent=1))

    def set_ptr_record(self, ip, ptr):
        r = requests.get(
            'https://api.64clouds.com/v1/setPTR?ip=' + ip + '&ptr=' + ptr + '&veid='
            + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    # no need
    def basic_shell_cd(self):
        pass

    def basic_shell_exec(self):
        pass

    def shell_script_exec(self):
        pass

    def snapshot_create(self, description='Automatic_Snapshot'):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/create?description=' + description + '&veid='
            + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def snapshot_list(self):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/list?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def snapshot_delete(self, snapshot):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/delete?snapshot=' + snapshot
            + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def snapshot_restore(self, snapshot):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/restore?snapshot=' + snapshot
            + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def snapshot_toggle_sticky(self, snapshot, sticky):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/toggleSticky?snapshot=' + snapshot
            + '&sticky=' + sticky + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def snapshot_export(self, snapshot):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/export?snapshot=' + snapshot
            + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def snapshot_import(self, source_veid, source_token):
        r = requests.get(
            'https://api.64clouds.com/v1/snapshot/import?sourceVeid=' + source_veid + '&sourceToken=' + source_token
            + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    # TODO need test if the ip is ipv4 or ipv6
    def ipv6_add(self, ip):
        r = requests.get(
            'https://api.64clouds.com/v1/ipv6/add?ip=' + ip + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def ipv6_delete(self, ip):
        r = requests.get(
            'https://api.64clouds.com/v1/ipv6/delete?ip=' + ip + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def migrate_get_locations(self):
        r = requests.get(
            'https://api.64clouds.com/v1/migrate/getLocations?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def migrate_start(self, location):
        r = requests.get(
            'https://api.64clouds.com/v1/migrate/start?location=' + location
            + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def clone_from_external_server(self, external_server_ip, external_server_ssh_port, external_server_root_password):
        server = self.get_server_info()
        if server.json()['vm_type'] != 'ovz':
            print( 'only for ovz servers')
            return False
        else:
            r = requests.get(
                'https://api.64clouds.com/v1/cloneFromExternalServer?externalServerIP=' + external_server_ip
                + '&externalServerSSHport=' + external_server_ssh_port + '&externalServerRootPassword'
                + external_server_root_password + '&veid=' + self.veid + '&api_key=' + self.api_key)
            print( json.dumps(r.json(), indent=1))

    def get_suspension_details(self):
        r = requests.get(
            'https://api.64clouds.com/v1/getSuspensionDetail?&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def unsuspend(self, record_id):
        r = requests.get(
            'https://api.64clouds.com/v1/unsuspend?record_id=' + record_id
            + '&veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))

    def get_rate_limit_status(self):
        r = requests.get(
            'https://api.64clouds.com/v1/getRateLimitStatus?veid=' + self.veid + '&api_key=' + self.api_key)
        print( json.dumps(r.json(), indent=1))


# 201 api_key: private_0e1rNKrmOAISlaEB53NNu3wO VEID: 1504295
# 216 api_key: private_d1v79PNnWrl47r7AtbwqFADa  VEID: 1360172
if __name__ == '__main__':

    #print(datetime.date.today() - relativedelta(months=+1))
    requests.get("http://124.223.11.108:9080/gUw5GwL3yRozyuTKCD2RBY/服务器流量检测/每日巡逻检验正常！")

    # do some test
    bwh = Bandwagonhost('1504295','private_0e1rNKrmOAISlaEB53NNu3wO')
    data = bwh.get_server_info()
    bwh = Bandwagonhost('1360172','private_d1v79PNnWrl47r7AtbwqFADa')
    data = bwh.get_server_info()

    # bwh.create_snapshot()
    # bwh.get_raw_usage_stats()
    # for keys in json.loads(data).keys():
    #    print( json.loads(data)[keys])